//
//  UUNotificationStateListVC.m
//  UUCharterSupplier
//
//  Created by ZhangAo on 23/01/2018.
//  Copyright © 2018 UUCharter. All rights reserved.
//

#import "UUNotificationStateListVC.h"
#import "UUNotificationManager.h"
#import "UUResourceManager.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "UUNotificationUtility.h"
#import "UUNotificationCell.h"

#define PAGE_LENGTH         (15)

@interface UUNotificationStateListVC () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, weak) IBOutlet UITableView *tableView;
@property (nonatomic, strong) UIImageView *emptyImageView;
@property (nonatomic, strong) NSMutableSet<Class> *registeredClasses;
@property (nonatomic, assign) UUNotificationType type;

@property (nonatomic, strong) NSMutableArray<UUNotificationModel *> *notifications;
@property (nonatomic, strong) id since;

@property (nonatomic, strong) UIButton *badgeView;

@end

@implementation UUNotificationStateListVC

+ (instancetype)listWithType:(UUNotificationType)type {
    UUNotificationStateListVC *listVC = [self instanceOfAppropriate];
    listVC.type = type;
    return listVC;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.registeredClasses = [NSMutableSet set];
    
    self.tableView.backgroundColor = COMMON_BACKGROUND_COLOR;
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    
    WEAK_SELF();
    self.tableView.mj_header = [UURefreshHeader headerWithRefreshingBlock:^{
        [weakSelf loadForFirst];
    }];
    
    self.tableView.mj_footer = [UURefreshFooter footerWithRefreshingBlock:^{
        [weakSelf loadMore];
    }];
    
    self.tableView.mj_footer.hidden = YES;
    
    [self.tableView.mj_header beginRefreshing];
//
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [self showNewNotificationBadge];
//    });
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)showNewNotificationBadge {
    if ([self isViewLoaded] && ![self.tableView.mj_header isRefreshing]) {
        if (self.badgeView == nil) {
            self.badgeView = [UIButton buttonWithType:UIButtonTypeCustom];
            [self.badgeView setImage:[UIImage imageNamed:@"NewBadge"] forState:UIControlStateNormal];
            [self.badgeView addTarget:self action:@selector(badgeViewDidTapped) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview:self.badgeView];
            [self.badgeView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.mas_equalTo(0);
                make.top.equalTo(self.mas_topLayoutGuideBottom).offset(10);
            }];
        }
        
        [self showsBadgeWithAnimation];
    }
}

#pragma mark - Private methods

- (void)badgeViewDidTapped {
    [self.tableView.mj_header beginRefreshing];
    [self hidesBadgeWithAnimation];
}

- (void)showsBadgeWithAnimation {
    self.badgeView.hidden = NO;
    self.badgeView.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, 0, -50);
    [UIView animateWithDuration:0.25 animations:^{
        self.badgeView.transform = CGAffineTransformIdentity;
    }];
}

- (void)hidesBadgeWithAnimation {
    self.badgeView.transform = CGAffineTransformIdentity;
    [UIView animateWithDuration:0.25 animations:^{
        self.badgeView.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, 0, -50);
    } completion:^(BOOL finished) {
        self.badgeView.hidden = YES;
//
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [self showNewNotificationBadge];
//        });
    }];
}

- (void)updateEmptyImageViewStatus {
    if (self.notifications.count == 0) {
        if (self.emptyImageView == nil) {
            self.emptyImageView = [[UIImageView alloc] initWithImage:GetResourceManager().emptyDataImage];
            [self.tableView addSubview:self.emptyImageView];
            [self.emptyImageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.mas_equalTo(0);
                make.top.mas_equalTo(100);
            }];
        }
        
        self.emptyImageView.hidden = NO;
    } else {
        self.emptyImageView.hidden = YES;
    }
}

- (void)loadForFirst {
    WEAK_SELF();
    [GetNotificationManager() asyncFetchNotificationsWithType:self.type
                                                        since:nil
                                                       length:PAGE_LENGTH
                                                completeBlock:^(NSArray<UUNotificationModel *> *notifications, id since, NSError *error) {
                                                    [weakSelf.tableView.mj_header endRefreshing];
                                                    
                                                    if (error == nil) {
                                                        weakSelf.notifications = [notifications mutableCopy];
                                                        weakSelf.since = since;
                                                        [weakSelf.tableView reloadData];
                                                        
                                                        weakSelf.tableView.mj_footer.hidden = notifications.count < PAGE_LENGTH;
                                                    } else {
                                                        ShowTipsOnView(error.localizedDescription, weakSelf.view);
                                                    }
                                                    
                                                    [weakSelf updateEmptyImageViewStatus];
                                                }];
}

- (void)loadMore {
    WEAK_SELF();
    [GetNotificationManager() asyncFetchNotificationsWithType:self.type
                                                        since:self.since
                                                       length:PAGE_LENGTH
                                                completeBlock:^(NSArray<UUNotificationModel *> *notifications, id since, NSError *error) {
                                                    [weakSelf.tableView.mj_footer endRefreshing];
                                                    
                                                    if (error == nil) {
                                                        weakSelf.tableView.mj_footer.hidden = notifications.count < PAGE_LENGTH;
 
                                                        [weakSelf.notifications addObjectsFromArray:notifications];
                                                        weakSelf.since = since;
                                                        
                                                        NSMutableArray<NSIndexPath *> *insertRows = [NSMutableArray arrayWithCapacity:notifications.count];
                                                        for (NSUInteger i = weakSelf.notifications.count - notifications.count; i < weakSelf.notifications.count; i++) {
                                                            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
                                                            [insertRows addObject:indexPath];
                                                        }
                                                        
                                                        [weakSelf.tableView insertRowsAtIndexPaths:insertRows withRowAnimation:UITableViewRowAnimationAutomatic];
                                                    } else {
                                                        ShowTipsOnView(error.localizedDescription, weakSelf.view);
                                                    }
                                                }];
}

- (Class)cellClassForIndexPath:(NSIndexPath *)indexPath {
    UUNotificationModel *notification = self.notifications[indexPath.row];
    return [UUNotificationUtility notificationCellForContentType:notification.content.type];
}

- (NSString *)cellReuseIdentifierForCell:(Class)cell {
    return NSStringFromClass([cell class]);
}

- (void)registerCellIfNeeded:(Class)cellClass {
    if ([self.registeredClasses containsObject:cellClass]) {
        return;
    }
    
    [self.tableView registerClass:cellClass forCellReuseIdentifier:[self cellReuseIdentifierForCell:cellClass]];
    [self.registeredClasses addObject:cellClass];
}

#pragma mark - UITableViewDelegate, UITableViewDataSource methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.notifications.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    Class cellClass = [self cellClassForIndexPath:indexPath];
    [self registerCellIfNeeded:cellClass];
    
    return [tableView fd_heightForCellWithIdentifier:[self cellReuseIdentifierForCell:cellClass]
                                    cacheByIndexPath:indexPath
                                       configuration:^(UUNotificationCell *cell) {
                                           UUNotificationModel *notification = self.notifications[indexPath.row];
                                           [cell setupWithModel:notification];
                                       }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    Class cellClass = [self cellClassForIndexPath:indexPath];
    UUNotificationCell *cell = [tableView dequeueReusableCellWithIdentifier:[self cellReuseIdentifierForCell:cellClass] forIndexPath:indexPath];
    
    UUNotificationModel *notification = self.notifications[indexPath.row];
    [cell setupWithModel:notification];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    UUNotificationModel *notification = self.notifications[indexPath.row];
    UIViewController *vc = [UUNotificationUtility targetVCWithNotification:notification];
    if (vc) {
        [self.navigationController pushViewController:vc animated:YES];
    }
}

@end
